//
// Created by Admin on 2021/9/22.
//

#include "my_stack.h"

pStack make_stack(){
    return calloc(1,sizeof(Stack));
}

void destroy_stack(pStack stack){
    while(pop(stack));
    free(stack);
}

void push(pStack stack,pItem item){
    if(stack->ebp == NULL){
        item->prev = NULL;
        stack->ebp = item;
        stack->esp = item;
    }else{
        item->prev = stack->esp;
        stack->esp = item;
    }
}

pItem peek(pStack stack){
    return stack->esp;
}

int pop(pStack stack){
    if(stack->esp != stack->ebp){
        pItem tmp = stack->esp->prev;
        free(stack->esp);
        stack->esp = tmp;
        return 1;
    }else{
        if(stack->ebp!=NULL){
            free(stack->ebp);
            stack->ebp = NULL;
            stack->esp = NULL;
        }
        return 0;
    }
}

void printStackTrace(pStack stack){
    pItem cur = stack->esp;
    while(cur){
        if(cur->type==number){
            printf("%d <- ",cur->value);
        }
        if(cur->type==character){
            printf("%c <- ",cur->value);
        }
        cur = cur->prev;
    }
}